package com.jaiky.imagespickers;

import com.jaiky.imagespickers.preview.ViewHolder;
import com.jaiky.imagespickers.utils.Utils;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;

import java.util.ArrayList;

/**
 * 加载相册图片的RecyclerView适配器
 * <p>
 * 用于替换原项目的GridView，使用局部刷新解决选中照片出现闪动问题
 * <p>
 * 替换为RecyclerView后只是不再会导致全局刷新，
 * <p>
 * 但还是会出现明显的重新加载图片，可能是picasso图片加载框架的问题
 * <p>
 * Author: nanchen
 * Email: liushilin520@foxmail.com
 * Date: 2017-04-05  10:04
 */

public class ImageAdapter extends BaseItemProvider {
    private static final int ITEM_TYPE_CAMERA = 0;  // 第一个条目是相机
    private static final int ITEM_TYPE_NORMAL = 1;  // 第一个条目不是相机
    private final ImagePicker imagePicker;
    private final Ability ability;
    private ArrayList<ImageItem> images;       // 当前需要显示的所有的图片数据
    private final ArrayList<ImageItem> mSelectedImages; // 全局保存的已经选中的图片数据
    private boolean isShowCamera;         // 是否显示拍照按钮
    private final int mImageSize;               // 每个条目的大小
    private final LayoutScatter mInflater;
    int selectLimit;

    /**
     * 刷新数据
     *
     * @param images images
     */
    public void refreshData(ArrayList<ImageItem> images) {
        isShowCamera = imagePicker.isShowCamera();
        if (images == null || images.size() == 0) {
            this.images = new ArrayList<>();
        } else {
            this.images = images;
        }
        notifyDataChanged();
    }

    /**
     * 构造方法
     *
     * @param ability ability
     * @param images  images
     */
    public ImageAdapter(Ability ability, ArrayList<ImageItem> images) {
        this.ability = ability;
        if (images == null || images.size() == 0) {
            this.images = new ArrayList<>();
        } else {
            this.images = images;
        }
        mImageSize = Utils.getImageItemWidth(this.ability);
        imagePicker = ImagePicker.getInstance();
        isShowCamera = imagePicker.isShowCamera();
        mSelectedImages = imagePicker.getSelectedImages();
        mInflater = LayoutScatter.getInstance(ability);
        selectLimit = imagePicker.getSelectLimit();
    }

    /**
     * onCreateViewHolder
     *
     * @param parent parent
     * @param viewType viewType
     * @return ViewHolder
     */
    public ViewHolder onCreateViewHolder(ComponentContainer parent, int viewType) {
        if (viewType == ITEM_TYPE_CAMERA) {
            return new CameraViewHolder(mInflater.parse(ResourceTable.Layout_imageselector_item_camera, parent, false));
        }
        return new ImageViewHolder(mInflater.parse(ResourceTable.Layout_imageselector_item_image, parent, false));
    }

    /**
     * onBindViewHolder
     *
     * @param holder holder
     * @param position position
     */
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (holder instanceof CameraViewHolder) {
            ((CameraViewHolder) holder).bindCamera();
        } else if (holder instanceof ImageViewHolder) {
            ((ImageViewHolder) holder).bind(position);
        }
    }

    @Override
    public int getItemComponentType(int position) {
        if (isShowCamera) {
            return position == 0 ? ITEM_TYPE_CAMERA : ITEM_TYPE_NORMAL;
        }
        return ITEM_TYPE_NORMAL;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        int type = getItemComponentType(i);
        ViewHolder viewHolder = onCreateViewHolder(componentContainer, type);
        onBindViewHolder(viewHolder, i);
        return viewHolder.getRootView();
    }

    @Override
    public int getCount() {
        return isShowCamera ? images.size() + 1 : images.size();
    }

    /**
     * getItem
     * @param position position
     * @return ImageItem
     */
    public ImageItem getItem(int position) {
        if (isShowCamera) {
            if (position == 0) {
                return null;
            }
            return images.get(position - 1);
        } else {
            return images.get(position);
        }
    }

    private class ImageViewHolder extends ViewHolder {
        Component rootView;
        Image ivThumb;
        Component mask;
        Checkbox cbCheck;

        ImageViewHolder(Component itemView) {
            rootView = itemView;
            ivThumb = (Image) itemView.findComponentById(ResourceTable.Id_photo_image);
            mask = itemView.findComponentById(ResourceTable.Id_photo_mask);
            cbCheck = (Checkbox) itemView.findComponentById(ResourceTable.Id_photo_check);
            rootView.setLayoutConfig(new ListContainer.LayoutConfig(mImageSize, mImageSize)); //让图片是个正方形
        }

        void bind(final int position) {
            final ImageItem imageItem = getItem(position);
            imagePicker.getImageLoader().displayImage(ability, imageItem.uriSchema, ivThumb); //显示图片
            if (imagePicker.getSelectedImages().size() > 0) {
                for (int i = 0; i < imagePicker.getSelectedImages().size(); i++) {
                    if (imageItem.uriSchema.equals(imagePicker.getSelectedImages().get(i).uriSchema)) {
                        cbCheck.setChecked(true);
                        mask.setVisibility(Component.VISIBLE);
                    }
                }
            }
            ivThumb.setClickedListener(view -> {
                if (selectLimit == 1) {
                    imagePicker.clear();
                    imagePicker.addSelectedImageItem(position, imageItem, true, 1);
                    if (imagePicker.getContainerAdapter() != null) {
                        imagePicker.getContainerAdapter().refreshData(imagePicker.getSelectedImages());
                    }
                    Intent intent = new Intent();
                    intent.setParam(ImagePicker.EXTRA_RESULT_ITEMS, imagePicker.getSelectedImages());
                    ability.setResult(ImagePicker.RESULT_CODE_ITEMS, intent);  // 多选不允许裁剪裁剪，返回数据
                    ability.terminateAbility();
                } else {
                    cbCheck.setChecked(!cbCheck.isChecked());
                    if (cbCheck.isChecked() && mSelectedImages.size() >= selectLimit) {
                        cbCheck.setChecked(false);
                        mask.setVisibility(Component.HIDE);
                        ImageSelectorAbility selectorAbility = (ImageSelectorAbility) ability;
                        selectorAbility.showToast("已经达到最高选择数量");
                    } else {
                        imagePicker.addSelectedImageItem(position, imageItem, cbCheck.isChecked(), 1);
                        mask.setVisibility(Component.VISIBLE);
                    }
                }
            });
            if (selectLimit == 1) {
                cbCheck.setVisibility(Component.HIDE);
                mask.setVisibility(Component.HIDE);
            } else {
                cbCheck.setVisibility(Component.VISIBLE);
            }
        }

        @Override
        public Component getRootView() {
            return rootView;
        }
    }

    private class CameraViewHolder extends ViewHolder {
        Component mItemView;

        CameraViewHolder(Component itemView) {
            mItemView = itemView;
        }

        void bindCamera() {
            mItemView.setLayoutConfig(new ListContainer.LayoutConfig(mImageSize, mImageSize)); // 让图片是个正方形
            mItemView.setTag(null);
            mItemView.setClickedListener(view -> {
                if (ability.verifySelfPermission(SystemPermission.CAMERA) != IBundleManager.PERMISSION_GRANTED) {
                    ability.requestPermissionsFromUser(new String[]{SystemPermission.CAMERA},
                            ImageSelectorAbility.REQUEST_PERMISSION_CAMERA);
                } else {
                    imagePicker.takePicture(ability);
                }
            });
        }

        @Override
        public Component getRootView() {
            return mItemView;
        }
    }
}
